package org.streets.database.handler;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.streets.database.RecordHandler;
import org.streets.database.RecordHandlerManager;



/**
 * Manager for simple {@link RecordHandler}.<br>
 * Each handler is associated with a {@link Class}
 * 
 * @author dzb
 * 
 */
public class BasicHandlerManager implements RecordHandlerManager {

	/**
	 * Mapping for classes - handlers
	 */
	protected final Map<Class<?>, RecordHandler<?>> HANDLER_CACHE = Collections.synchronizedMap(new HashMap<Class<?>, RecordHandler<?>>());	
	protected final Logger logger;
	
	public BasicHandlerManager(Logger logger) {
		this.logger = logger;
	}

	public <T> void register(Class<T> clazz, RecordHandler<T> handler) {
		// checks
		if (clazz == null) {
			throw new NullPointerException("Class cannot be null");
		}
		
		if (handler == null) {
			throw new NullPointerException("Handler cannot be null");
		}
		
		if (!HANDLER_CACHE.containsKey(clazz)) {
			HANDLER_CACHE.put(clazz, handler);
		} else {
			logger.warn("Entity ["+clazz+"] has been registered already!");
		}		

	}

	@SuppressWarnings("unchecked")
	public <T> RecordHandler<T> getHandler(Class<T> key) {
		return (RecordHandler<T>) HANDLER_CACHE.get(key);
	}
}
